//
//  status.swift
//  sinaWeiBo
//
//  Created by weixq on 15/8/6.
//  Copyright © 2015年 weixq. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String? {
        didSet{
            source = source?.hrefLink().text
        }
    }
    /// 配图数组
    var pic_urls: [[String: AnyObject]]?{
        didSet {
            if pic_urls!.count == 0 {
            return
            }
            
            storedPictureURLs = [NSURL]()
            storedLagrePictureURLs = [NSURL]()
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    // 生成缩略图的URL
                    storedPictureURLs?.append(NSURL(string: urlString)!)
                    
                    // 大图的URL
                   let largeURL =  urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    storedLagrePictureURLs?.append(NSURL(string: largeURL)!)
                }
            }
        }
    }
     /// 保存转发微博的配图URL
    private var storedPictureURLs:[NSURL]?
     /// 保存配图的大图 URL 的数组
    private var storedLagrePictureURLs:[NSURL]?
    
    /// 配图的URL的计算型数组
    /// 如果是原创微博，返回storedPictureRULs
    /// 如果是转发微博，返回 retweed_status.storedPictureURLs
    var pictureURLs: [NSURL]?{
        return retweeted_status == nil ? storedPictureURLs : retweeted_status?.storedPictureURLs
    }
    
     /// 返回大图的URL数组
    var largePictureURLs: [NSURL]? {
        return retweeted_status == nil ? storedLagrePictureURLs : retweeted_status?.storedLagrePictureURLs
    }
    
    
    
    /// 用户
    var user: User?
    
    var rowHight: CGFloat?
    
    // 被转发的原微博信息字段，当该微博为转发微博时返回
    var retweeted_status: Status?
    
    // MARK: - 构造函数
    init(dic: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
                user = User(dict: dict)
            }
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject] {
                retweeted_status = Status(dic: dict)
            }
            return
        }
        
        
        
        super.setValue(value, forKey: key)
    }
    
    // 加载微博数据，返回 微博数据的数组
    class func loadStatus(since_id: Int, max_id: Int,finished: (datalist: [Status]?, error: NSError?) -> ()){
        
        NetworkTools.sharedTools.loadstatus(since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                finished(datalist: nil, error: error)
            }
            
            // 判断是否获得字典数组
            
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                
                // 遍历数组，字典转模型
                var list = [Status]()
                
                for dict in array {
                    list.append(Status(dic: dict))
                }
                
                // 缓存图片
                cacheWebImage(list, finished: finished)

            
            }else{
                finished(datalist: nil, error: nil)
            }
        }
    
    }
    
    // 缓存微博的网络图片，缓存结束后，才属性数据
    private class func cacheWebImage(list: [Status], finished: (datalist: [Status]?, error: NSError?) -> ()) {
        // 创建调度组
        let group = dispatch_group_create()
        
        // 缓存图片大小
        var dataLength = 0
        
        // 循环遍历数组
        for status in list {

            // 判断是否有图片
            guard let urls = status.pictureURLs else {
                continue
            }
            
            // 遍历urls的数组，缓存图片
            for imageUrl in urls {
                
                // 入组
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) in
                    
                    // 如果下载图像失败，image 转换到二进制数据的时候，会报错
                    if image != nil {
                    
                        let data = UIImagePNGRepresentation(image)!
                        dataLength += data.length

                    }
                    
                    dispatch_group_leave(group)
                })
                
            
            }
        }
        
        // 监听所有缓存操作的通知
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
           finished(datalist: list, error: nil)
        }
    }
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String{
        let keys = ["created_at", "id", "text", "source", "pic_urls"]
        return "\(dictionaryWithValuesForKeys(keys))"
    }
}
